import { _decorator, Animation, Button, CapsuleCollider, Color, Component, director, Event, find, game, instantiate, JsonAsset, Label, labelAssembler, log, Material, MeshRenderer, nextPow2, Node, Prefab, resources, SkeletalAnimation, Sprite, SpriteFrame, sys, Tween, tween, UIOpacity, v3, Vec3, Widget } from 'cc';
import { GameManager } from './GameManager';
import Banner from './Banner';
import { PlayerController } from './PlayerController';
import { AudioManager } from './AudioManager';
import { ZTool } from './ZTool';
import { Player } from '../Player';
const { ccclass, property } = _decorator;

@ccclass('UIManager')
export class UIManager extends Component {

    private static _instance: UIManager = null;
    public static get Instance(): UIManager {
        if (!this._instance) {
            this._instance = new UIManager();
        }
        return this._instance;
    }

    @property({ type: Node })
    Main: Node = null;
    @property({ type: Node })
    Running: Node = null;
    @property({ type: Node })
    Fight: Node = null;
    @property({ type: Node })
    End: Node = null;
    @property({ type: Node })
    MonsterBgContent: Node = null;

    onLoad() {
        UIManager._instance = this;
        // sys.localStorage.clear();//清空数据缓存
    }

    MonsterItems = ["陶伦", "普迪普迪", "粉温奇", "火狮", "斯凯利", "乌龟", "史蒂文", "马菲",
        "鸿基", "小鸟", "莫蒂", "诺米", "妈咪大长腿", "末影人", "泰迪", "蓝色的", "弗兰基",
        "发光少女", "绿兽", "雷神", "捣蛋鬼", "神蜥"];

    start() {
        this.Main.getChildByName("Diamond").getComponentInChildren(Label).string = GameManager.Instance.GetLocalStorage("Diamond").toString();
        for (let i in this.MonsterItems) {
            resources.load("Prefabs/MonsterItem", Prefab, (err, pre) => {
                let item = instantiate(pre);
                resources.load("Texture/CardRole/" + this.MonsterItems[i] + "/spriteFrame", SpriteFrame, (err, spf) => {
                    item.getChildByName("Img").getComponent(Sprite).spriteFrame = spf;
                })
                item.setParent(this.MonsterBgContent);
            })
        }
    }

    update(deltaTime: number) {

    }

    InitMonsterItem() {
        for (let i in this.MonsterItems) {
            if (GameManager.Instance.GetLocalStorage(this.MonsterItems[i]) == 1) {
                let item = this.MonsterBgContent.children[i];
                item.getComponent(Sprite).grayscale = false;
                item.getChildByName("Img").getComponent(Sprite).grayscale = false;
                item.getChildByName("Lock").active = false;
                item.getChildByName("Choose").active = true;
            }
        }
    }

    AddMoneyNum(num: number) {
        Banner.Instance.vibrateShort();
        GameManager.Instance.MoneyNum += num;
        this.Running.getChildByName("Money").getComponentInChildren(Label).string = GameManager.Instance.MoneyNum.toFixed(0).toString();
        GameManager.Instance.UpdateAllCardTop();
        this.ShowSingleMoney();
    }

    SubMoneyNum(num: number) {
        Banner.Instance.vibrateShort();
        let money = GameManager.Instance.MoneyNum;
        GameManager.Instance.MoneyNum -= num;
        if (GameManager.Instance.MoneyNum < 0) { GameManager.Instance.MoneyNum = 0; }
        tween(this.node)
            .delay(0.01)
            .call(() => {
                money--;
                if (money < 0) { money = 0; }
                this.Running.getChildByName("Money").getComponentInChildren(Label).string = money.toFixed(0).toString();
            })
            .union()
            .repeat(num)
            .start()
        GameManager.Instance.UpdateAllCardTop();
    }

    ShowSingleMoney() {
        resources.load("Prefabs/SingleMoney", Prefab, (err, pre) => {
            let single = instantiate(pre);
            single.setParent(this.Running.getChildByName("SingleMoneyInit"));
            this.scheduleOnce(() => {
                single.destroy();
            }, 0.5)
        })
    }

    ShowFailedPanel() {//失败结算
        if (!this.End.getChildByName("FailedPanel").active) {
            AudioManager.Instance.playSound("Audio/Failed");
            this.End.getChildByName("FailedPanel").active = true;
            let failedBg = this.End.getChildByName("FailedPanel").getChildByName("FailedBg");
            let skipBtn = this.End.getChildByName("FailedPanel").getChildByName("SkipBtn");
            tween(failedBg)
                .to(0.8, { scale: v3(1.05, 1.05) })
                .to(0.8, { scale: v3(1, 1) })
                .union()
                .repeatForever()
                .start();
            tween(failedBg.getChildByName("CryFace"))
                .to(1, { angle: -20 })
                .to(1, { angle: 20 })
                .union()
                .repeatForever()
                .start();
            tween(skipBtn.getChildByName("video"))
                .to(1, { scale: v3(0.8, 0.8), angle: -10 })
                .to(1, { scale: v3(1, 1), angle: 10 })
                .union()
                .repeatForever()
                .start();
            Banner.Instance.ShowNativeAd();
        }
    }

    ShowWinPanel() {//胜利结算
        if (!this.End.getChildByName("WinPanel").active) {
            AudioManager.Instance.playSound("Audio/Win");
            let winBg = this.End.getChildByName("WinPanel").getChildByName("WinBg");
            let continueBtn = this.End.getChildByName("WinPanel").getChildByName("ContinueBtn");
            winBg.scale = Vec3.ZERO;
            continueBtn.active = false;
            this.End.getChildByName("WinPanel").active = true;
            tween(winBg)
                .to(0.8, { scale: v3(1, 1) }, { easing: "backOut" })
                .call(() => { continueBtn.active = true; Banner.Instance.ShowNativeAd(); })
                .start();
        }
    }

    ////////////////////////////////////////////////////按钮点击事件///////////////////////////////////////////////////////
    OnRoleBtnClicked(event: Event) {//查看角色
        AudioManager.Instance.playSound("Audio/Button");
        let roleBg = this.Main.getChildByName("RolePanel").getChildByName("RoleBg");
        roleBg.scale = Vec3.ZERO;
        for (let i = 0; i < roleBg.getChildByName("Role").children.length; i++) {
            resources.load("Texture/Lock/spriteFrame", SpriteFrame, (err, spf) => {
                roleBg.getChildByName("Role").children[i].getComponent(Sprite).spriteFrame = spf;
            })
            roleBg.getChildByName("Role").children[i].getChildByName("Choose").active = false;
            if (GameManager.Instance.GetLocalStorage("UnLockRole" + i) == 1) {
                roleBg.getChildByName("Role").children[i].getChildByName("Price").active = false;
            }
        }
        resources.load("Texture/UnLock/spriteFrame", SpriteFrame, (err, spf) => {
            roleBg.getChildByName("Role").children[GameManager.Instance.GetLocalStorage("Role")].getComponent(Sprite).spriteFrame = spf;
        })
        roleBg.getChildByName("Role").children[GameManager.Instance.GetLocalStorage("Role")].getChildByName("Choose").active = true;
        this.Main.getChildByName("RolePanel").active = true;
        tween(roleBg)
            .to(0.5, { scale: Vec3.ONE }, { easing: "backOut" })
            .call(() => { Banner.Instance.ShowNativeAd(); })
            .start()
    }
    OnRolePanelCloseBtnClicked(event: Event) {//角色界面关闭按钮
        AudioManager.Instance.playSound("Audio/Button");
        this.Main.getChildByName("RolePanel").active = false;
    }
    OnRoleItem1Clicked(event: Event) {//初始角色
        AudioManager.Instance.playSound("Audio/Button");
        for (let i = 0; i < event.target.parent.children.length; i++) {
            resources.load("Texture/Lock/spriteFrame", SpriteFrame, (err, spf) => {
                event.target.parent.children[i].getComponent(Sprite).spriteFrame = spf;
            })
            event.target.parent.children[i].getChildByName("Choose").active = false;
        }
        resources.load("Texture/UnLock/spriteFrame", SpriteFrame, (err, spf) => {
            event.target.getComponent(Sprite).spriteFrame = spf;
        })
        event.target.getChildByName("Choose").active = true;
        if (GameManager.Instance.PlayerInit.children[0].name != "Player0") {
            GameManager.Instance.MainCamera.setParent(director.getScene());
            GameManager.Instance.PlayerInit.children[0].destroy();
            GameManager.Instance.SetLocalStorage("Role", 0);
            resources.load("Prefabs/Player/Player" + GameManager.Instance.GetLocalStorage("Role"), Prefab, (err, pre) => {
                let player = instantiate(pre);
                PlayerController.Instance.PlayerScript = player.getComponent(Player);
                player.setParent(GameManager.Instance.PlayerInit);
            })
        }
    }
    OnRoleItem2Clicked(event: Event) {//鸣人
        AudioManager.Instance.playSound("Audio/Button");
        if (event.target.getChildByName("Price").active) {
            if (event.target.getChildByName("Price").getChildByName("Num").active) {
                let num = Number(event.target.getChildByName("Price").getComponentInChildren(Label).string);
                if (GameManager.Instance.GetLocalStorage("Diamond") >= num) {
                    GameManager.Instance.SetLocalStorage("Diamond", GameManager.Instance.GetLocalStorage("Diamond") - num);
                    this.Main.getChildByName("Diamond").getComponentInChildren(Label).string = GameManager.Instance.GetLocalStorage("Diamond").toString();
                    this.OnRoleItem2CallBack(event.target);
                }
                else {
                    this.ShowTipLabelByString("所持宝石数量不足！", Vec3.ZERO, Color.WHITE);
                    event.target.getChildByName("Price").getChildByName("Num").active = false;
                    event.target.getChildByName("Price").getChildByName("Video").active = true;
                }
            }
            else {
                //视频解锁
                Banner.Instance.ShowVideo(this.OnRoleItem2CallBack, event.target);
            }
        }
        else {
            this.OnRoleItem2CallBack(event.target);
        }
    }
    OnRoleItem2CallBack(btn: Node) {//鸣人按钮回调
        for (let i = 0; i < btn.parent.children.length; i++) {
            resources.load("Texture/Lock/spriteFrame", SpriteFrame, (err, spf) => {
                btn.parent.children[i].getComponent(Sprite).spriteFrame = spf;
            })
            btn.parent.children[i].getChildByName("Choose").active = false;
        }
        resources.load("Texture/UnLock/spriteFrame", SpriteFrame, (err, spf) => {
            btn.getComponent(Sprite).spriteFrame = spf;
        })
        btn.getChildByName("Price").active = false;
        btn.getChildByName("Choose").active = true;
        if (GameManager.Instance.PlayerInit.children[0].name != "Player1") {
            GameManager.Instance.MainCamera.setParent(director.getScene());
            GameManager.Instance.PlayerInit.children[0].destroy();
            GameManager.Instance.SetLocalStorage("Role", 1);
            GameManager.Instance.SetLocalStorage("UnLockRole1", 1);
            resources.load("Prefabs/Player/Player" + GameManager.Instance.GetLocalStorage("Role"), Prefab, (err, pre) => {
                let player = instantiate(pre);
                PlayerController.Instance.PlayerScript = player.getComponent(Player);
                player.setParent(GameManager.Instance.PlayerInit);
            })
        }
    }
    OnRoleItem3Clicked(event: Event) {//小丑女
        AudioManager.Instance.playSound("Audio/Button");
        if (event.target.getChildByName("Price").active) {
            if (event.target.getChildByName("Price").getChildByName("Num").active) {
                let num = Number(event.target.getChildByName("Price").getComponentInChildren(Label).string);
                if (GameManager.Instance.GetLocalStorage("Diamond") >= num) {
                    GameManager.Instance.SetLocalStorage("Diamond", GameManager.Instance.GetLocalStorage("Diamond") - num);
                    this.Main.getChildByName("Diamond").getComponentInChildren(Label).string = GameManager.Instance.GetLocalStorage("Diamond").toString();
                    this.OnRoleItem3CallBack(event.target);
                }
                else {
                    this.ShowTipLabelByString("所持宝石数量不足！", Vec3.ZERO, Color.WHITE);
                    event.target.getChildByName("Price").getChildByName("Num").active = false;
                    event.target.getChildByName("Price").getChildByName("Video").active = true;
                }
            }
            else {
                //视频解锁
                Banner.Instance.ShowVideo(this.OnRoleItem3CallBack, event.target);
            }
        }
        else {
            this.OnRoleItem3CallBack(event.target);
        }
    }
    OnRoleItem3CallBack(btn: Node) {//小丑女按钮回调
        for (let i = 0; i < btn.parent.children.length; i++) {
            resources.load("Texture/Lock/spriteFrame", SpriteFrame, (err, spf) => {
                btn.parent.children[i].getComponent(Sprite).spriteFrame = spf;
            })
            btn.parent.children[i].getChildByName("Choose").active = false;
        }
        resources.load("Texture/UnLock/spriteFrame", SpriteFrame, (err, spf) => {
            btn.getComponent(Sprite).spriteFrame = spf;
        })
        btn.getChildByName("Price").active = false;
        btn.getChildByName("Choose").active = true;
        if (GameManager.Instance.PlayerInit.children[0].name != "Player2") {
            GameManager.Instance.MainCamera.setParent(director.getScene());
            GameManager.Instance.PlayerInit.children[0].destroy();
            GameManager.Instance.SetLocalStorage("Role", 2);
            GameManager.Instance.SetLocalStorage("UnLockRole2", 1);
            resources.load("Prefabs/Player/Player" + GameManager.Instance.GetLocalStorage("Role"), Prefab, (err, pre) => {
                let player = instantiate(pre);
                PlayerController.Instance.PlayerScript = player.getComponent(Player);
                player.setParent(GameManager.Instance.PlayerInit);
            })
        }
    }
    OnMonsterBtnClicked(event: Event) {//查看怪物图鉴
        AudioManager.Instance.playSound("Audio/Button");
        let monsterBg = this.Main.getChildByName("MonsterPanel").getChildByName("MonsterBg");
        monsterBg.scale = Vec3.ZERO;
        this.InitMonsterItem();
        this.Main.getChildByName("MonsterPanel").active = true;
        tween(monsterBg)
            .to(0.5, { scale: Vec3.ONE }, { easing: "backOut" })
            .call(() => { Banner.Instance.ShowNativeAd(); })
            .start()
    }
    OnMonsterPanelCloseBtnClicked(event: Event) {//角色界面关闭按钮
        AudioManager.Instance.playSound("Audio/Button");
        this.Main.getChildByName("MonsterPanel").active = false;
    }
    OnSkipBtnClicked(event: Event) {//跳过此关
        AudioManager.Instance.playSound("Audio/Button");
        Banner.Instance.ShowVideo(this.OnSkipBtnCallBack);
    }
    OnSkipBtnCallBack() {
        let nextlevel: number;
        if (GameManager.Instance.GetLocalStorage("Level") + 1 >= 15) {
            nextlevel = ZTool.getRandomIntWithMax(0, 14);
        }
        else {
            nextlevel = GameManager.Instance.GetLocalStorage("Level") + 1;
        }
        GameManager.Instance.SetLocalStorage("Level", nextlevel);
        GameManager.Instance.SetLocalStorage("LevelTitle", GameManager.Instance.GetLocalStorage("LevelTitle") + 1);
        director.loadScene("Loading");
    }
    OnAgainBtnClicked(event: Event) {//重玩
        AudioManager.Instance.playSound("Audio/Button");
        director.loadScene("Loading");
    }
    OnContinueBtnClicked(event: Event) {//继续
        AudioManager.Instance.playSound("Audio/Button");
        let nextlevel: number;
        if (GameManager.Instance.GetLocalStorage("Level") + 1 >= 15) {
            nextlevel = ZTool.getRandomIntWithMax(0, 14);
        }
        else {
            nextlevel = GameManager.Instance.GetLocalStorage("Level") + 1;
        }
        GameManager.Instance.SetLocalStorage("Level", nextlevel);
        GameManager.Instance.SetLocalStorage("LevelTitle", GameManager.Instance.GetLocalStorage("LevelTitle") + 1);
        GameManager.Instance.SetLocalStorage("Diamond", GameManager.Instance.GetLocalStorage("Diamond") + 20);
        director.loadScene("Loading");
    }

    OnStartFightBtnClicked(event: Event) {//开始战斗
        AudioManager.Instance.playSound("Audio/Button");
        event.target.active = false;
        PlayerController.Instance.TakeOffTouch();
        switch (GameManager.Instance.EnemyMonsters.length) {
            case 1:
                {
                    GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[0], GameManager.Instance.EnemyMonsters[0]);
                    GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[1], GameManager.Instance.EnemyMonsters[0]);
                    GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[2], GameManager.Instance.EnemyMonsters[0]);
                }
                break;
            case 2:
                {
                    GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[1], GameManager.Instance.EnemyMonsters[1]);
                    this.scheduleOnce(() => {
                        GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[0], GameManager.Instance.EnemyMonsters[0]);
                    }, 1)
                }
                break;
            case 3:
                {
                    GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[2], GameManager.Instance.EnemyMonsters[2]);
                    this.scheduleOnce(() => {
                        GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[1], GameManager.Instance.EnemyMonsters[1]);
                        this.scheduleOnce(() => {
                            GameManager.Instance.Fight(GameManager.Instance.PlayerMonsters[0], GameManager.Instance.EnemyMonsters[0]);
                        }, 1)
                    }, 1)
                }
                break;
        }
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    //提示信息
    ShowTipLabelByString(str: string, pos: Vec3 = Vec3.ZERO, color: Color = Color.GRAY) {
        resources.load("Prefabs/TipLabel", Prefab, (err, pre) => {
            let tiplabel = instantiate(pre);
            tiplabel.getComponent(UIOpacity).opacity = 0;
            tiplabel.getComponent(Label).string = str;
            tiplabel.getComponent(Label).color = color;
            tiplabel.setPosition(pos);
            tiplabel.setParent(find("Canvas"));
            tiplabel.setPosition(tiplabel.getPosition().x, tiplabel.getPosition().y - 30);
            tween(tiplabel.getComponent(UIOpacity))
                .to(0.5, { opacity: 255 })
                .delay(1)
                .to(0.5, { opacity: 0 })
                .start();
            tween(tiplabel)
                .to(0.5, { position: v3(tiplabel.getPosition().x, tiplabel.getPosition().y + 30) })
                .delay(1)
                .to(0.5, { position: v3(tiplabel.getPosition().x, tiplabel.getPosition().y + 60) })
                .call(() => {
                    tiplabel.destroy();
                })
                .start();
        })
    }
}


